package net.a6polo.a6poloweibo;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.LinkedList;
import java.util.List;

import net.a6polo.a6poloweibo.util.A6poloUtil;
import net.a6polo.a6poloweibo.util.RenrenParamer;
import net.a6polo.renren.RenrenAPIV2;
import net.a6polo.renren.domain.ErrorCode;
import net.a6polo.renren.domain.ErrorRequest;
import net.a6polo.renren.domain.UserInfo;
import net.a6polo.renren.net.RequestListener;
import net.a6polo.renren.ui.RenrenFeedActivity;
import net.a6polo.service.Service;
import net.a6polo.service.SnsType;
import net.a6polo.service.domain.Account;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class RenrenIndexActivity extends Activity {

	private Exception exception;
	private Service service;
	private WebView webView;
	private String accessToken = null;
	private String refresh_token = null;
	private long id;
	//private SharedData share;
	String authUrl = "https://graph.renren.com/oauth/authorize?client_id="
			+ RenrenParamer.appId
			+ "&response_type=token"
			+ "&redirect_uri=http://graph.renren.com/oauth/login_success.html"
			+ "&scope=status_update photo_upload";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_renren_index);
		service = new Service(RenrenIndexActivity.this);
		webView = (WebView) findViewById(R.id.web);

		bindViews();

	}
	
	private void bindViews() {  
        WebSettings settings = webView.getSettings();  
        settings.setJavaScriptEnabled(true);  
        settings.setSupportZoom(true);  
        settings.setBuiltInZoomControls(true);  
        webView.loadUrl(authUrl);  
        webView.requestFocusFromTouch();  
  
        WebViewClient wvc = new WebViewClient() {  
            @Override  
            public void onPageFinished(WebView view, String url) {  
                super.onPageFinished(view, url);  
                //人人网用户名和密码验证通过后，刷新页面时即可返回accessToken  
                String reUrl = webView.getUrl();  
                
               // Log.d(GlobalData.TAG, "reUrl:" + reUrl);  
                if (reUrl.indexOf("access_token") != -1) {  
                    //截取url中的accessToken  
                    int startPos = reUrl.indexOf("token=") + 6;  
                    int endPos = reUrl.indexOf("&expires_in");  
                    accessToken = reUrl.substring(startPos, endPos);  
                    accessToken = URLDecoder.decode(accessToken);
                    
                    int refresh_tokenStartPos = reUrl.indexOf("refresh_token") + 13;
                    int refresh_tokenEndPos = reUrl.indexOf("&scope");
                    refresh_token =  reUrl.substring(refresh_tokenStartPos, refresh_tokenEndPos);  
                    refresh_token = URLDecoder.decode(refresh_token);
                    
                    Log.d("a6polo", "---------renren accessToken:" + accessToken);  
                    
                    Account renrenAccount = new Account();
                    renrenAccount.setAccessToken(accessToken);
                    renrenAccount.setRefreshToken(refresh_token);
                    renrenAccount.setType(SnsType.RENREN);
                    id = service.addAccount(renrenAccount);
                    Log.d("a6polo", "---------renren account id:" + id); 
                    Toast.makeText(RenrenIndexActivity.this, "验证成功", Toast.LENGTH_SHORT).show();
                    
                    RenrenAPIV2 renrenAPI = new RenrenAPIV2(RenrenIndexActivity.this);
                    renrenAPI.getUserInfo(new UserInfoRequestListener());
                }  
            }  
        };  
        webView.setWebViewClient(wvc);  
       
    }  
	
	class UserInfoRequestListener implements RequestListener {

		@Override
		public void onComplete(String response) {
			Gson gson = new Gson();
			Log.d("a6polo", "result:" + response);
			
			Type listType = new TypeToken<LinkedList<UserInfo>>(){}.getType();
			List<UserInfo> userInfoList = gson.fromJson(response, listType);
			UserInfo userInfo = userInfoList.get(0);
			Account account = service.getAccount(id);
			account.setUid(userInfo.getUid());;
			account.setUserName(userInfo.getName());
			service.update(account);
			
			Intent intent = new Intent();
    		intent.setClass(RenrenIndexActivity.this, IndexActivity.class);
    		startActivity(intent);
            finish(); 
		}

		@Override
		public void onIOException(IOException e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}

		@Override
		public void onError(Exception e) {
			exception = e;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), " error : " + exception.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			});
		}
		
	}

}
